package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.dto.ProductDockingDTO;
import com.yami.shop.bean.model.*;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.dao.ProductDockedMapper;
import com.yami.shop.dao.ProductDockingMapper;
import com.yami.shop.service.*;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 商品对接Service实现类
 */
@Service
@Slf4j
public class ProductDockingServiceImpl extends ServiceImpl<ProductDockingMapper, ProductDocking> implements ProductDockingService {

    @Resource
    private MessageSource messageSource;
    
    @Autowired
    private ProductService productService;
    @Autowired
    ShopSubagentService shopSubagentService;
    
    @Autowired
    private ShopSettingService shopSettingService;
    @Autowired
    private ProductDockingMapper productDockingMapper;
    @Autowired
    private ProductDockedMapper productDockedMapper;
    @Autowired
    private ShopCategoryService shopCategoryService;

    @Override
    public IPage<ProductDockingDTO> pageProductDocking(Page<ProductDockingDTO> page, Long shopId, String prodName, Integer dockingStatus) {
        return baseMapper.pageProductDocking(page, shopId, prodName, dockingStatus);
    }

    @Override
    public ProductDockingDTO getProductDockingById(Long id) {
        if (id == null) {
            throw new YamiShopBindException(messageSource.getMessage("product.docking.id.not.null", null, LocaleContextHolder.getLocale()));
        }
        return baseMapper.getProductDockingById(id);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void applyProductDocking(Long prodId, Long categoryId, Double fareIncrease, Long shopId, String name,Long id) {

        // 验证商品是否存在
        Product product = productService.getById(prodId);
        ShopCategory shopCategory = shopCategoryService.getById(categoryId);
        if (product == null) {
            throw new YamiShopBindException(messageSource.getMessage("product.not.exist", null, LocaleContextHolder.getLocale()));
        }
        if (shopCategory == null) {
            throw new YamiShopBindException(messageSource.getMessage("shopCategory.not.exist", null, LocaleContextHolder.getLocale()));
        }
        ProductDocking productDocking = productDockingMapper.selectById(id);
        ShopSetting shopSetting = shopSettingService.getShopSetting(productDocking.getShopId());
        if (shopSetting.getAuditStatus() == 0){
            ShopSubagent shopSubagent = new ShopSubagent();
            shopSubagent.setSubShopId(shopId);
            shopSubagent.setShopId(productDocking.getShopId());
            shopSubagent.setAuditStatus(0);
            shopSubagentService.save(shopSubagent);
            return;
        }

        ShopSubagent shopSubagent = new ShopSubagent();
        shopSubagent.setSubShopId(shopId);
        shopSubagent.setShopId(productDocking.getShopId());
        shopSubagent.setAuditStatus(1);
        shopSubagentService.save(shopSubagent);

        ProductDocked productDocked = new ProductDocked();
        // 设置商品分类ID
        productDocked.setShopCategoryId(categoryId);
        productDocked.setProdId(prodId);
        productDocked.setShopId(shopId);
        productDocked.setName(name);
        productDocked.setCategoryName(shopCategory.getCategoryName());
        productDocked.setCostPrice(BigDecimal.valueOf(product.getProxyFarePrice()));
        productDocked.setPrice(BigDecimal.valueOf(fareIncrease + product.getProxyFarePrice()));
        productDocked.setSupShopId(productDocking.getShopId());
        productDocked.setSupProdName(product.getProdName());
        // 设置创建时间和更新时间
        Date now = new Date();
        productDocked.setCreateTime(now);
        productDocked.setUpdateTime(now);
        if (productDockedMapper.insert(productDocked) == 0) {
            throw new YamiShopBindException(messageSource.getMessage("product.docking.apply.failed", null, LocaleContextHolder.getLocale()));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditProductDocking(Long id, Integer dockingStatus, String rejectReason) {
        if (id == null) {
            throw new YamiShopBindException(messageSource.getMessage("product.docking.id.not.null", null, LocaleContextHolder.getLocale()));
        }
        
        if (dockingStatus == null || (dockingStatus != 1 && dockingStatus != 2)) {
            throw new YamiShopBindException(messageSource.getMessage("product.docking.status.invalid", null, LocaleContextHolder.getLocale()));
        }
        
        ProductDocking productDocking = getById(id);
        if (productDocking == null) {
            throw new YamiShopBindException(messageSource.getMessage("product.docking.not.exist", null, LocaleContextHolder.getLocale()));
        }
        
        if (productDocking.getDockingStatus() != 0) {
            throw new YamiShopBindException(messageSource.getMessage("product.docking.already.audited", null, LocaleContextHolder.getLocale()));
        }
        
        // 更新对接状态
        productDocking.setDockingStatus(dockingStatus);
        productDocking.setAuditTime(new Date());
        productDocking.setUpdateTime(new Date());
        
        // 如果拒绝，设置拒绝原因
        if (dockingStatus == 2 && rejectReason != null) {
            productDocking.setRejectReason(rejectReason);
        }
        
        boolean result = updateById(productDocking);
        if (!result) {
            throw new YamiShopBindException(messageSource.getMessage("product.docking.audit.failed", null, LocaleContextHolder.getLocale()));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelProductDocking(Long id) {
        if (id == null) {
            throw new YamiShopBindException(messageSource.getMessage("product.docking.id.not.null", null, LocaleContextHolder.getLocale()));
        }
        
        ProductDocking productDocking = getById(id);
        if (productDocking == null) {
            throw new YamiShopBindException(messageSource.getMessage("product.docking.not.exist", null, LocaleContextHolder.getLocale()));
        }
        
        boolean result = removeById(id);
        if (!result) {
            throw new YamiShopBindException(messageSource.getMessage("product.docking.cancel.failed", null, LocaleContextHolder.getLocale()));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int dockProductsByCategory(Long shopId, Long categoryId) {
        if (shopId == null || categoryId == null) {
            return 0;
        }
        return baseMapper.batchInsertByCategoryId(shopId, categoryId);
    }
} 